package com.gaga.common.utils;

import com.gaga.common.result.ReplaceTextResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
public class TemplateReplacer {

    /**
     * 处理润色之后的话术文本
     *
     * @param template
     * @return
     */
    public static String replacePolishText(String template, String userName, String userCallName) {
        if (StringUtils.isBlank(template)) {
            return template;
        }
        //包含下面中文直接返回不用播报
        String regex = "改写|润色|回复";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(template);

        if (matcher.find()) {
            return "";
        }

        // 正则表达式匹配 "亲" 后的中英文逗号或感叹号
        String replaceRegex = "亲[，,!！.。]";

        template = template.replaceAll(replaceRegex, "");

        template = NumberConverter.convertAmountInText(template);

        template = LetterTranslator.translate(template);

        log.error("template:{},userName:{}", template, userName);
        if (StringUtils.isNotBlank(userName) && !template.contains(userName)) {
            template = userName + template;
        }
        template = template.replaceAll("\\[[^\\]]*\\]", "");

        if (StringUtils.isNotBlank(userCallName)) {
            template = removePunctuationBeforeGege(template, userCallName);
        }

        template = replaceChinesePunctuation(template);

        template = template.replaceAll(
                "[^a-zA-Z0-9\\p{P}\\p{script=Han}]",
                ""
        );

//        template = template.replaceAll("[,。，！!]", ".");

        return template;
    }

    public static ReplaceTextResult replaceParameters(String template, String userName, String userCount, Integer queueSize) {
        ReplaceTextResult result = new ReplaceTextResult();
        if (StringUtils.isBlank(userName)) {
            userName = "";
        }
        userName = userName.replaceAll("[\\p{C}\\p{So}\\p{Sm}\\p{Sc}\\p{Sk}\\p{Me}]", "");

        userName = NumberConverter.convertArabicToChinese(userName);

        if (StringUtils.isBlank(userCount)) {
            userCount = "";
        }
        // 处理 [名字] 替换
        template = template.replace("[名字]", userName);

        // 处理 [人数] 替换
        template = template.replace("[人数]", userCount);

        LocalDateTime currentTime = LocalDateTime.now();

        DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("M月d日", Locale.CHINESE); // 示例输出: 3月5日
        String formattedDate = currentTime.format(formatter);
        template = template.replace("[日期]", formattedDate);

        // 生成 30-60 秒之间的随机值，时间向后退后 30-60 秒
        int randomSeconds = new Random().nextInt(10) + (queueSize.intValue() * 5); // 30到60（含）
        LocalDateTime futureTime = currentTime.plus(randomSeconds, ChronoUnit.SECONDS);

        String formattedTime = formatTimeWithChinesePeriod(futureTime);
        template = template.replace("[时间]", formattedTime);

        template = template.replaceAll("\\[[^\\]]*\\]", "");

        // 处理 {家人们|宝贝们|哥哥姐姐们} 随机选择
        template = randomSelectText(template);

        template = replaceChinesePunctuation(template);

        template = removeEmojiAndSpecialChars(template);

        template = template.replaceAll(
                "[^a-zA-Z0-9\\p{P}\\p{script=Han}]",
                ""
        );


//        template = template.replaceAll("[,。，！!]", ".");
        result.setText(template);
        result.setFutureTime(futureTime);
        return result;
    }

    public static String removeEmojiAndSpecialChars(String input) {
        if (input == null) {
            return null;
        }

        // 正则表达式匹配:
        // - 基本汉字: \u4e00-\u9fa5
        // - 数字: 0-9
        // - 大小写字母: a-zA-Z
        // - 一些常见中文标点: ，。？！、；："'（）《》【】
        Pattern pattern = Pattern.compile("[^\u4e00-\u9fa5a-zA-Z0-9,.?!:，。？！、；：\"'（）《》【】]");
        Matcher matcher = pattern.matcher(input);
        return matcher.replaceAll("");
    }

    public static String randomSelectText(String template) {
        int startIndex = template.indexOf("{");
        while (startIndex != -1) {
            int endIndex = template.indexOf("}", startIndex);
            if (endIndex != -1) {
                String optionsStr = template.substring(startIndex + 1, endIndex);
                String[] options = optionsStr.split("\\|");
                Random random = new Random();
                String selectedOption = options[random.nextInt(options.length)];
                template = template.substring(0, startIndex) + selectedOption + template.substring(endIndex + 1);
            } else {
                break;
            }
            startIndex = template.indexOf("{", startIndex);
        }
        return template;
    }

    public static String formatTimeWithChinesePeriod(LocalDateTime time) {
        // 获取时间段（凌晨/上午/中午/下午/晚上）
        String period = getChinesePeriod(time);
        // 格式化时间为 h点mm分（12小时制）
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h点mm分", Locale.CHINESE);
        String timePart = time.format(timeFormatter);
        return period + timePart;
    }

    private static String getChinesePeriod(LocalDateTime time) {
        int hour = time.getHour();
        if (hour >= 0 && hour < 6) {
            return "凌晨";
        } else if (hour >= 6 && hour < 11) {
            return "上午";
        } else if (hour >= 11 && hour < 13) {
            return "中午";
        } else if (hour >= 13 && hour < 18) {
            return "下午";
        } else {
            return "晚上";
        }
    }


    public static String removePunctuationBeforeGege(String input, String userCallName) {
        int index = input.indexOf(userCallName);

        if (index != -1 && index > 0) {
            // 检查目标词前的字符是否为中文/英文逗号
            char prevChar = input.charAt(index - 1);
            if (prevChar == '，' || prevChar == ',' || prevChar == '.' || prevChar == '。') {
                // 拼接删除标点后的字符串
                return input.substring(0, index - 1) + input.substring(index);
            }
        }
        return input;
    }

    public static String replaceChinesePunctuation(String text) {
        // 创建中文标点到英文标点的映射表
        Map<String, String> chineseToEnglish = new HashMap<>();
        chineseToEnglish.put("，", ",");
        chineseToEnglish.put("。", ".");
        chineseToEnglish.put("！", "!");
        chineseToEnglish.put("？", "?");
        chineseToEnglish.put("；", ";");
        chineseToEnglish.put("：", ":");
        chineseToEnglish.put("“", "\"");
        chineseToEnglish.put("”", "\"");
        chineseToEnglish.put("‘", "'");
        chineseToEnglish.put("’", "'");
        chineseToEnglish.put("（", "(");
        chineseToEnglish.put("）", ")");
        chineseToEnglish.put("【", "[");
        chineseToEnglish.put("】", "]");
        chineseToEnglish.put("《", "<");
        chineseToEnglish.put("》", ">");
        chineseToEnglish.put("—", "-");
        chineseToEnglish.put("…", "...");
        chineseToEnglish.put("、", ",");

        // 构建正则表达式模式，使用Pattern.quote确保特殊字符被转义
        String patternStr = chineseToEnglish.keySet()
                .stream()
                .map(Pattern::quote)
                .collect(Collectors.joining("|"));
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(text);

        // 使用StringBuffer进行替换
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String matched = matcher.group();
            // 获取对应的英文标点，如果找不到则保留原字符（此处根据需求可以调整）
            String replacement = chineseToEnglish.getOrDefault(matched, matched);
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    public static void main(String[] args) {

        String s = " {哥姐们|.哥哥姐}们|大哥大姐}们|宝兹们你们放心购买带走。收到货后不会做的，无需担忧，每袋背面都有详细制作方法。粉和水按1比25的比例调配，新手按此操作也能一次做成功。";

        Pattern EMOJI_PATTERN = Pattern.compile("\\[[^\\]]*\\]");

        System.out.println(EMOJI_PATTERN.matcher("[微笑]123").replaceAll(""));
//        System.out.println("[微笑]123".replaceAll("\$$[^\$$]*\\]", ""));
        String s1 = removeEmojiAndSpecialChars(s);
        System.out.println(s1);

        int leftBraceCount = StringUtils.countMatches(s, "{");
        int rightBraceCount = StringUtils.countMatches(s, "}");
        System.out.println(removePunctuationBeforeGege(s, "哥哥"));
//        System.out.println(rightBraceCount);

        String userName = "Test😊→✔$^ABC\u0007";

        userName = userName.replaceAll("[\\p{C}\\p{So}\\p{Sm}\\p{Sc}\\p{Sk}\\p{Me}]", "");

        System.out.println(userName);
//        String template = "欢迎[名字]姐姐来到直播间，现在直播间[人数]位家人，现在[时间]，{家人们|宝贝们|哥哥姐姐们}，库存已经所剩不多了，没有有拍的抓紧时间拍了。";
//        String name = "小美";
//        String peopleCount = "50";
//        String result = replaceParameters(template, name, peopleCount);
//        System.out.println(result);
//
//        LocalTime currentTime = LocalTime.now();
//        String time24Format = currentTime.format(DateTimeFormatter.ofPattern("HH:mm"));
//        String script24 = String.format("家人们，现在是北京时间 %s，咱们直播间活动火热进行中，千万别错过！", time24Format);
//        System.out.println(script24);
//
//        // 12 小时制话术
//        String time12Format = currentTime.format(DateTimeFormatter.ofPattern("h:mm a"));
//        String script12 = String.format("家人们，现在是北京时间 %s，抓紧时间下单啦！", time12Format);
//        System.out.println(script12);
//
//        // 定义中文12小时制格式（带上午/下午，并将“时”改为“点”）
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ah点mm分", Locale.CHINESE);
//        // 格式化时间
//        String time12Chinese = currentTime.format(formatter);
//
//        System.out.println(time12Chinese);

    }

}